import axios from 'axios';
import { getStore, setStore } from './storage';
import { router } from '../router/index';
import { Message } from 'view-design';
import Cookies from 'js-cookie';
import crypto from '@/libs/secret';
// 统一请求路径前缀
let baseApi = config.baseApi;
// 超时设定
axios.defaults.timeout = 1800000;

axios.interceptors.request.use(
    config => {
        if (config.data) {
            for (let key in config.data) {
                if (config.data[key] == undefined) {
                    config.data[key] = '';
                }
            }
            //config.data = JSON.parse(JSON.stringify(config.data).replaceAll(undefined, ""));
        }
        // config.headers.tablename = getStore("tableName")
        config.headers.tablename = Cookies.get('tableName');
        config.headers.parttablename = getStore('partTableName');
        return config;
    },
    err => {
        Message.error({
            duration: 5,
            content: '请求超时',
            closable: true
        });
        return Promise.resolve(err);
    }
);

// http response 拦截器
axios.interceptors.response.use(
    response => {
        const data = response.data;
        const config = response.config;

        // 根据返回的code值来做不同的处理(和后端约定)
        switch (data.code) {
            case 200:
                if (data.message === '登录成功' || data.result === null || data.result === '') {
                    return data;
                }
                if (!data.result) {
                    return data;
                }
                let result = JSON.parse(crypto.decrypt(data.result));
                data.result = result;
                return data;
                break;
            case 401:
                // 未登录 清除已登录状态
                Cookies.set('userInfo', '');
                setStore('accessToken', '');
                console.log(router.history, 'router.history.current.name');
                if (router.history.current.name != 'edulogin' || router.history.current.name != 'prologin') {
                    if (data.message !== null) {
                        router.push(router.history.current.path);

                        // Message.error(data.message);
                        Message.error({
                            duration: 5,
                            content: data.message,
                            closable: true
                        });
                    } else {
                        Message.error({
                            duration: 5,
                            content: '未知错误，请重新登录',
                            closable: true
                        });
                        // Message.error("未知错误，请重新登录");
                    }
                    // router.push('/login');
                }
                break;
            case 403:
                // 没有权限
                if (data.message !== null) {
                    Message.error({
                        duration: 5,
                        content: data.message,
                        closable: true
                    });
                    // Message.error(data.message);
                } else {
                    Message.error({
                        duration: 5,
                        content: '未知错误',
                        closable: true
                    });
                    // Message.error("未知错误");
                }
                break;
            case 500:
                console.log("data.message", data.message);
                let noMessageUrlList =['/xboot/dataAuditWarning/add']
                if(noMessageUrlList.includes(config.url)){
                    return data;
                }

                // 错误
                if (data.message !== null) {
                    Message.error({
                        duration: 5,
                        content: data.message,
                        closable: true
                    });
                    // Message.error(data.message);
                } else {
                    Message.error({
                        duration: 5,
                        content: '未知错误',
                        closable: true
                    });
                    // Message.error("未知错误");
                }
                break;
            default:
                
                // Message.error({
                //     duration: 5,
                //     content: '操作失败，请联系管理员',
                //     closable: true
                // });

                // if (data.message === '登录成功' || data.result === null || data.result === '') {
                //     return data;
                // }
                // if (!data.result) {
                //     return data;
                // }
                // let result = JSON.parse(crypto.decrypt(data.result));
                // data.result = result;
                // return data;
        }
        return data;
    },
    err => {
        // 返回状态码不为200时候的错误处理
        // Message.error(err.toString());
        Message.error({
            content: err.toString(),
            duration: 5,
            closable: true
        });
        return Promise.resolve(err);
    }
);
export const getRequestToken = (token, url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'get',
        url: `${baseApi}${url}`,
        params: params,
        headers: {
            accessToken: token
        }
    });
};
/**
 * 请求数据加密JSON格式。
 * @param url
 * @param params
 * @returns {AxiosPromise}
 */
export const postEncryptRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'post',
        url: `${baseApi}${url}`,
        data: params,
        transformRequest: [
            function (data) {
                return data;
            }
        ],
        headers: {
            'Content-Type': 'application/json',
            accessToken: accessToken
        }
    });
};

export const getRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'get',
        url: `${baseApi}${url}`,
        params: params,
        headers: {
            accessToken: accessToken
        }
    });
};

export const postRequestToken = (token, url, params) => {
    // let accessToken = getStore("accessToken");
    return axios({
        method: 'post',
        url: `${baseApi}${url}`,
        data: params,
        transformRequest: [
            function (data) {
                let ret = '';
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                ret = ret.substring(0, ret.length - 1);
                return ret;
            }
        ],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            accessToken: token
        }
    });
};

export const postRequest = (url, params, config = {}) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'post',
        url: `${baseApi}${url}`,
        data: params,
        transformRequest: [
            function (data) {
                let ret = '';
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                ret = ret.substring(0, ret.length - 1);
                return ret;
            }
        ],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            accessToken: accessToken
        },
        ...config
    });
};
export const exportPost = (url, params,method) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: method|| 'post',
        url: `${baseApi}${url}`,
        data: params,
        transformRequest: [
            function (data) {
                let ret = '';
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                ret = ret.substring(0, ret.length - 1);
                return ret;
            }
        ],
        responseType: 'blob',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            accessToken: accessToken
        }
    });
};

export const putRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'put',
        url: `${baseApi}${url}`,
        data: params,
        transformRequest: [
            function (data) {
                let ret = '';
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                ret = ret.substring(0, ret.length - 1);
                return ret;
            }
        ],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            accessToken: accessToken
        }
    });
};

export const postBodyRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'post',
        url: `${baseApi}${url}`,
        data: params,
        headers: {
            accessToken: accessToken
        }
    });
};

export const bodyPostRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'post',
        url: `${baseApi}${url}`,
        data:  params,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            accessToken: accessToken
        }
    });
};

export const importRequestData = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'post',
        url: `${baseApi}${url}`,
        data: params,
        // 去除post请求默认的Content-Type
        headers: {
            'Content-Type': 'multipart/form-data',
            accessToken: accessToken
        }
    });
};

/**
 * 无需token验证的GET请求 避免旧token过期导致请求失败
 * @param {*} url
 * @param {*} params
 */
export const getNoAuthRequest = (url, params) => {
    return axios({
        method: 'get',
        url: `${baseApi}${url}`,
        params: params
    });
};

export const postNoAuthRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${baseApi}${url}`,
        data: params,
        transformRequest: [
            function (data) {
                let ret = '';
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                ret = ret.substring(0, ret.length - 1);
                return ret;
            }
        ],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
};

export const importRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'post',
        url: `${baseApi}${url}`,
        data: params,
        headers: {
            accessToken: accessToken
        }
    });
};
